<template>
  <div :style="{height:height,width:width}" />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import { debounce } from "@/utils";

export default {
  props: {
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "500px"
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      }
    }
  },
  mounted() {
    this.initChart();

    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize();
      }
    }, 100);
    window.addEventListener("resize", this.__resizeHandler);
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    if (this.autoResize) {
      window.removeEventListener("resize", this.__resizeHandler);
    }

    this.sidebarElm &&
      this.sidebarElm.removeEventListener(
        "transitionend",
        this.sidebarResizeHandler
      );

    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    sidebarResizeHandler(e) {
      if (e.propertyName === "width") {
        this.__resizeHandler();
      }
    },
    setOptions({ expectedData, actualData } = {}) {
      const _this = this;
      this.chart.setOption({
        grid: {
          // 设置直角坐标系
          top: 50,
          left: "2%",
          right: "2%",
          bottom: "4%",
          containLabel: true
        },
        tooltip: {
          // 设置提示框
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        toolbox: {
          // 设置工具栏
          show: true,
          right: "2%",
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        xAxis: [
          // 设置直角坐标系 grid 中的 x 轴
          {
            type: "category",
            data: this.chartData.xName,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(params, index) {
                let ret = ""; // 拼接加\n返回的类目项
                const maxLength = 5; // 每项显示文字个数
                const valLength = params.length; // X轴类目项的文字个数
                const rowN = Math.ceil(valLength / maxLength); // 类目项需要换行的行数
                if (rowN > 1) {
                  // 如果类目项的文字大于3,
                  for (let i = 0; i < rowN; i++) {
                    let temp = ""; // 每次截取的字符串
                    const start = i * maxLength; // 开始截取的位置
                    const end = start + maxLength; // 结束截取的位置
                    temp = params.substring(start, end) + "\n";
                    ret += temp; // 拼接最终的字符串
                  }
                  return ret;
                } else {
                  return params;
                }
              }
            }
          }
        ],
        yAxis: [
          // 设置直角坐标系 grid 中的 y 轴
          {
            type: "value",
            axisTick: {
              show: false
            }
          }
        ],
        legend: {
          // 设置图例
          data: this.chartData.showName
        },
        dataZoom: [
          // 设置区域缩放
          {
            type: "inside",
            end: _this.chartData.barData.length > 20 ? "50" : "100"
          },
          {
            type: "slider",
            end: _this.chartData.barData.length > 20 ? "50" : "100",
            bottom: 0
          }
        ],
        series: [
          // 设置系列列表(图表类型相关)
          {
            name: this.chartData.showName,
            type: "bar",
            barWidth: "18%",
            stack: "vistors",
            label: {
              // 顶部文字的显示
              show: true, // 开启显示
              position: "top", // 在上方显示
              fontSize: 12,
              formatter: function(params, index) {
                // 显示内容转换为百分比
                let percent =
                  (parseInt(params.data) / (_this.chartData.total - 0)) * 100;
                percent = percent.toFixed(2) + "%";
                return percent;
              }
            },
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#83bff6" },
                  { offset: 0.5, color: "#188df0" },
                  { offset: 1, color: "#188df0" }
                ])
              },
              emphasis: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#2378f7" },
                  { offset: 0.7, color: "#2378f7" },
                  { offset: 1, color: "#83bff6" }
                ])
              }
            },
            data: this.chartData.barData,
            animationDuration: 4000,
            animationEasing: "quadraticOut"
          }
        ]
      });
    },
    async initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    }
  }
};
</script>
